Page({
  data: {
    searchKeyword: '',
    activeTab: 'recipe',
    searchHistory: [],
    hotSearchTags: [],
    categories: [
      { id: 1, name: '川菜', icon: '/images/category/sichuan.png' },
      { id: 2, name: '粤菜', icon: '/images/category/guangdong.png' },
      { id: 3, name: '湘菜', icon: '/images/category/hunan.png' },
      { id: 4, name: '鲁菜', icon: '/images/category/shandong.png' },
      { id: 5, name: '苏菜', icon: '/images/category/jiangsu.png' },
      { id: 6, name: '浙菜', icon: '/images/category/zhejiang.png' },
      { id: 7, name: '闽菜', icon: '/images/category/fujian.png' },
      { id: 8, name: '徽菜', icon: '/images/category/anhui.png' }
    ],
    recipeResults: [],
    userResults: [],
    loading: false
  },

  onLoad(options) {
    // 从本地存储获取搜索历史
    const history = wx.getStorageSync('searchHistory') || [];
    this.setData({
      searchHistory: history
    });

    // 加载热门搜索Top10
    this.loadHotKeywords();
  },

  // 搜索输入
  onSearchInput(e) {
    const keyword = e.detail.value;
    this.setData({
      searchKeyword: keyword
    });
    
    if (keyword) {
      this.search(keyword);
    }
  },

  // 搜索确认
  onSearchConfirm(e) {
    const keyword = e.detail.value;
    if (keyword.trim()) {
      this.performSearch(keyword);
    }
  },

  // 清除搜索
  onClearSearch() {
    this.setData({
      searchKeyword: '',
      recipeResults: [],
      userResults: []
    });
  },

  // 取消搜索
  onCancel() {
    wx.navigateBack();
  },

  // 标签点击
  onTagTap(e) {
    const tag = e.currentTarget.dataset.tag;
    this.setData({
      searchKeyword: tag
    });
    this.performSearch(tag);
  },

  // 历史记录点击
  onHistoryTap(e) {
    const keyword = e.currentTarget.dataset.keyword;
    this.setData({
      searchKeyword: keyword
    });
    this.performSearch(keyword);
  },

  // 清除历史记录
  onClearHistory() {
    wx.showModal({
      title: '提示',
      content: '确定要清除搜索历史吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            searchHistory: []
          });
          wx.removeStorageSync('searchHistory');
        }
      }
    });
  },

  // 分类点击
  onCategoryTap(e) {
    const category = e.currentTarget.dataset.category;
    this.setData({
      searchKeyword: category.name
    });
    this.performSearch(category.name);
  },

  // 标签切换
  onTabChange(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      activeTab: tab
    });
  },

  // 菜谱点击
  onRecipeTap(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/detail/detail?id=${id}`
    });
  },

  // 用户点击
  onUserTap(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/user/user?id=${id}`
    });
  },

  // 关注用户
  onFollowTap(e) {
    const id = e.currentTarget.dataset.id;
    const userResults = this.data.userResults.map(user => {
      if (user.id === id) {
        return { ...user, isFollowed: !user.isFollowed };
      }
      return user;
    });
    
    this.setData({
      userResults: userResults
    });

    // 这里可以调用API更新关注状态
    wx.showToast({
      title: userResults.find(u => u.id === id).isFollowed ? '已关注' : '已取消关注',
      icon: 'success'
    });
  },

  // 执行搜索
  performSearch(keyword) {
    // 保存搜索历史
    this.saveSearchHistory(keyword);
    
    // 执行搜索
    this.search(keyword);
  },

  // 搜索功能
  search(keyword) {
    if (!keyword.trim()) return;
    this.setData({ loading: true });

    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
    }

    wx.request({
      url: 'http://localhost/dev-api/recipes/recipes/list',
      method: 'GET',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      data: {
        pageNum: 1,
        pageSize: 10,
        title: keyword
      },
      success: (res) => {
        const ok = res.data && res.data.code === 200;
        const rows = ok ? (res.data.rows || []) : [];
        const recipeResults = rows.map(item => {
          let imageUrl = 'https://picsum.photos/300/200?random=1';
          if (item.mediaType === 2) {
            imageUrl = item.videoDescription ? `http://localhost:8080${item.videoDescription}` : imageUrl;
          } else if (item.mediaType === 1) {
            imageUrl = item.coverUrl ? `http://localhost:8080${item.coverUrl}` : imageUrl;
          }
          return {
            id: item.id,
            title: item.title || '',
            imageUrl: imageUrl,
            authorName: (item.users && item.users.nickname) ? item.users.nickname : '美食达人',
            authorAvatar: (item.users && item.users.avatarUrl) ? `http://localhost:8080${item.users.avatarUrl}` : 'https://picsum.photos/60/60?random=1',
            views: item.viewCount || 0,
            likes: item.likeCount || 0,
            comments: item.commentCount || 0
          };
        });

        this.setData({
          recipeResults: recipeResults,
          userResults: [],
          loading: false
        });

        if (recipeResults.length > 0) {
          this.logSearchKeyword(keyword);
        }
      },
      fail: (err) => {
        console.error('搜索失败', err);
        this.setData({ loading: false });
        wx.showToast({ title: '搜索失败', icon: 'none' });
      }
    });
  },

  // 生成用户搜索结果（暂无真实接口，保持空）
  generateUserResults(keyword) {
    return [];
  },

  // 保存搜索历史
  saveSearchHistory(keyword) {
    let history = this.data.searchHistory;
    
    // 移除已存在的相同关键词
    history = history.filter(item => item !== keyword);
    
    // 添加到开头
    history.unshift(keyword);
    
    // 只保留最近10条
    history = history.slice(0, 10);
    
    this.setData({
      searchHistory: history
    });
    
    // 保存到本地存储
    wx.setStorageSync('searchHistory', history);
  }
  ,

  // 加载热门搜索关键词Top10
  loadHotKeywords() {
    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
    }

    wx.request({
      url: 'http://localhost/dev-api/recipes/search_logs/list',
      method: 'GET',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      data: { pageNum: 1, pageSize: 100 },
      success: (res) => {
        if (res.data && res.data.code === 200) {
          const rows = res.data.rows || [];
          const counter = new Map();
          rows.forEach(item => {
            const kw = (item.keyword || '').trim();
            if (!kw) return;
            counter.set(kw, (counter.get(kw) || 0) + 1);
          });
          const top10 = Array.from(counter.entries())
            .sort((a, b) => b[1] - a[1])
            .slice(0, 10)
            .map(([kw], idx) => ({ id: idx + 1, name: kw }));
          this.setData({ hotSearchTags: top10 });
        }
      },
      fail: (err) => {
        console.error('加载热门搜索失败', err);
      }
    });
  },

  // 记录搜索关键词
  logSearchKeyword(keyword) {
    let token = '';
    let userId = null;
    try {
      token = wx.getStorageSync('token');
      const userInfo = wx.getStorageSync('userInfo') || {};
      userId = userInfo.id || null;
    } catch (e) {
      console.error('读取本地信息失败', e);
    }

    wx.request({
      url: 'http://localhost/dev-api/recipes/search_logs',
      method: 'POST',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      data: {
        userId: userId,
        keyword: keyword
      }
    });
  }
}); 